#!/usr/bin/python
# -*- coding: utf-8 -*- 

import requests
import json
import sys
import os
from telnetlib import Telnet
import time
import datetime
##### 传入参数含义：Username用户名，Password密码，Host主机名称，Command执行命令
##### 方法含义：get_sw_bytes获取当前核心交换机字节数 get_fw_bytes获取当前防火墙字节数 get_ping获取当前ping（复用） get_week_day获取当前星期几 findSubStrIndex取出现第几次str的下标 msg为钉钉调用接口方法 get_memusage 获取内存占用
##### get_bytes返回list，list[0]为下载字节数，list[1]为上传，get_ping返回值为平均延迟
##### main方法写死字符串拼接
from pip._internal.utils import logging

headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "https://oapi.dingtalk.com/robot/send?access_token="



#####时间字典
def get_week_day(date):
  week_day_dict = {
    0 : '星期一',
    1 : '星期二',
    2 : '星期三',
    3 : '星期四',
    4 : '星期五',
    5 : '星期六',
    6 : '星期天',
  }
  day = date.weekday()
  return week_day_dict[day] 
#print(get_week_day(datetime.datetime.now()))
####函数意义：取字符串substr在str中出现第time次的下标
def findSubStrIndex(substr, str, time):
    times = str.count(substr)
    if (times == 0) or (times < time):
        pass
    else:
        i = 0
        index = -1
        while i < time:
            index = str.find(substr, index+1)
            i+=1
        return index

def get_ping(Username,Password,Host,command):
    tn = Telnet()

    try:

        tn.open(Host, port=23)

    except:

        logging.warning('Failed')

    tn.read_until(b'Username:', timeout=10)

    tn.write(Username.encode('ascii') + b'\n')

    tn.read_until(b'Password:', timeout=10)

    tn.write(Password.encode('ascii') + b'\n')

    time.sleep(1)

    command_result = tn.read_very_eager().decode('ascii')

    print(command_result)

    time.sleep(1)

    tn.write(command.encode('ascii') + b'\n')

    tn.write('exit'.encode('ascii') + b'\n')

    time.sleep(1)

    #print("write is done-------".encode('utf-8'))
    #info = str(tn.read_all().encode('utf-8'))
    info = str(tn.read_very_eager().encode('utf-8'))
    a = 0
    a = findSubStrIndex("/",info,4)
    #print("a-------------------",a)
    info = info[a+1:a+5]
    #print("info------",info)
    return info

def get_sw_bytes(Username,Password,Host,Command):
    tn = Telnet()

    try:

        tn.open(Host, port=23)

    except:

        logging.warning('Failed')

    tn.read_until(b'Username:', timeout=10)

    tn.write(Username.encode('ascii') + b'\n')

    tn.read_until(b'Password:', timeout=10)

    tn.write(Password.encode('ascii') + b'\n')

    time.sleep(1)

    command_result = tn.read_very_eager().decode('ascii')

    print(command_result)

    #tn.write('terminal length 0'.encode('ascii') + b'\n')

    time.sleep(1)

    tn.write(Command.encode('ascii') + b'\n')
    a = 0
    while a < 27:
        a = a + 1
        tn.write('\n')
    tn.write('exit'.encode('ascii') + b'\n')

    
    time.sleep(1)
    info = str(tn.read_very_eager().encode('utf-8'))
    
    b = info.find("Last 300 seconds input")
    c = info.find("Input (total)")
    info = info[b:c].replace("---- More ----","")
    list = []
    d = info.rfind("packets/sec")
    e = info.find("packets/sec")
    f = info.find("bytes/sec")
    g = info.rfind("bytes/sec")
    input = info[e+12:f-1]
    output = info[d+12:g-1]
    list.append(input)
    list.append(output)
    network = "下载速度为"+input +"\t" + "上传速度为"+output
    return list


def get_fw_bytes(Username,Password,Host,Command):
    tn = Telnet()

    try:

        tn.open(Host, port=23)

    except:

        logging.warning('Failed')

    tn.read_until(b'Username:', timeout=10)

    tn.write(Username.encode('ascii') + b'\n')

    tn.read_until(b'Password:', timeout=10)

    tn.write(Password.encode('ascii') + b'\n')

    time.sleep(1)

    command_result = tn.read_very_eager().decode('ascii')

    print(command_result)

    time.sleep(1)

    tn.write(Command.encode('ascii') + b'\n')

    tn.write('exit'.encode('ascii') + b'\n')
    
    time.sleep(1)
    info = str(tn.read_very_eager().encode('utf-8'))
    list = []
    b = info.find("Last 300 seconds input")
    c = info.find("Last 300 seconds output")
    f = info.find("bytes/sec")
    g = info.rfind("bytes/sec")
    input = info[b+29:f-1]
    output = info[c+30:g-1]
    list.append(input)
    list.append(output)
    network = "downlaod----"+input +"\t" + "uplaod------"+output
    return list

def get_memusage(Username,Password,Host,command):
    tn = Telnet()

    try:

        tn.open(Host, port=23)

    except:

        logging.warning('Failed')

    tn.read_until(b'Username:', timeout=10)

    tn.write(Username.encode('ascii') + b'\n')

    tn.read_until(b'Password:', timeout=10)

    tn.write(Password.encode('ascii') + b'\n')

    time.sleep(1)

    command_result = tn.read_very_eager().decode('ascii')

    print(command_result)

    time.sleep(1)

    tn.write(command.encode('ascii') + b'\n')

    tn.write('exit'.encode('ascii') + b'\n')

    time.sleep(1)

    info = str(tn.read_very_eager().encode('utf-8'))
    a = 0
    #a = findSubStrIndex("/",info,4)
    a = info.find("-/+")
    info = info[a-8:a-4]
    a = 100 - float(info)
    print(a)
    return a
def msg(text):
    json_text= {
     "msgtype": "text",
        "at": {
            "atMobiles": [
                "17xxxxxxx46"
            ],
            "isAtAll": False
        },
        "text": {
            "content": text
        }
    }
    print (requests.post(api_url, json.dumps(json_text), headers=headers).content())
    
if __name__ == '__main__':
#    text = sys.argv[1]
    year = time.strftime("%Y", time.localtime())
    month = time.strftime("%m", time.localtime())
    day =  time.strftime("%d", time.localtime())
    zx_list = get_sw_bytes('guest','123@456.com','10.37.253.254','dis int gig 2/2/0/22')
    zx_ping = get_ping('guest','123@456.com','10.37.253.254','ping 10.255.1.137')
    a = round(float(zx_list[0])/1024/1024*8/110,2)*100
    b = round(float(zx_list[1])/1024/1024*8/110,2)*100
    print("zx_list-------",zx_list)
    msg1 = "联通110M专线：  下载负荷"+str(a) + "%" +  "," + "上传负荷" + str(b)+ "%" + "," + "时延" + zx_ping + "ms"
    cmcc_list = get_fw_bytes('guest','123@456.com','10.37.253.253','dis int reth 2')
    cmcc_ping = get_ping('guest','123@456.com','10.37.253.253','ping  111.35.4.129')
    c = round(float(cmcc_list[0])/1024/1024*8/110,2)*100
    d = round(float(cmcc_list[1])/1024/1024*8/110,2)*100
    msg2 = "移动100M互联网：下载负荷" + str(c) + "%"+  "," + "上传负荷" + str(d)+ "%"+ "," + "时延" + cmcc_ping + "ms"
    unicom_list = get_fw_bytes('guest','123@456.com','10.37.253.253','dis int reth 1')
    unicom_ping = get_ping('guest','123@456.com','10.37.253.253','ping 61.162.221.254')
    e = round(float(unicom_list[0])/1024/1024*8/200,2)*100
    f = round(float(unicom_list[1])/1024/1024*8/200,2)*100
    msg3 = "联通200M互联网：下载负荷" + str(e) + "%"+  "," + "上传负荷" + str(f)+ "%"+ "," + "时延" + unicom_ping + "ms"
    bg_mem = get_memusage("dianjian","123@456.com","10.37.253.251","dis memory")
    sc_mem = get_memusage("dianjian","123@456.com","10.37.253.252","dis memory")
    msg0 = year + "年" + month + "月" + day + "日   " + get_week_day(datetime.datetime.now()) + "\n" + "运营技术科网络监控运行情况如下：" + "\n" + "生产汇聚内存：" + str(sc_mem) + "%" + "\n" + "办公汇聚内存：" + str(bg_mem) + "%" + "\n" + msg1 + "\n" + msg3 + "\n" + msg2
    print(msg0)
    #msg(msg0)

